import React, { useEffect, useState } from "react";
import { useTranslation } from "react-i18next";
import "./index.scss";
import { Select, Button, Table, message, Modal } from "antd";
import {
  PlusOutlined,
  EditOutlined,
  DeleteOutlined,
  SearchOutlined,
  ExclamationCircleFilled,
} from "@ant-design/icons";
import { text_check, post_axios } from "../../utils";
import RolePower from "./rolePower";
import EditRole from "./editRole";

export default function Role(props) {
  const { t } = useTranslation();
  const { confirm } = Modal;
  const [tableHeight, setTableHeight] = useState(0);
  const { actions, setSpinning } = props;
  let { menu_action, user_power_lang, username } = actions;
  user_power_lang = JSON.parse(user_power_lang);

  let localStorage_company = JSON.parse(localStorage.getItem("choose_company"));
  const local_company_object =
    localStorage_company &&
    localStorage_company[username] &&
    localStorage_company[username]
      ? localStorage_company[username]
      : "";

  //  角色列表筛选
  const [action_value, setAction_value] = useState("");
  // 级别拆解对象
  const [grade_object, setGrade_object] = useState({});

  const [role_action_array, setRole_action_array] = useState("");
  //菜单权限列表
  const [menu_power_array, setMenu_power_array] = useState([]);
  //菜单权限列表，用于添加时进行初始化
  const [menu_power_array_initial, setMenu_power_array_initial] = useState([]);
  // 角色列表
  const [role_list, setRole_list] = useState([]);
  // 角色绑定的用户
  const [role_user_list, setRole_user_list] = useState([]);
  // 查询角色授权的模块
  const [role_action_list, setRole_action_list] = useState([]);
  // 添加角色
  const [edit_role_show, setEdit_role_show] = useState(false);
  const [edit_role_title, setEdit_role_title] = useState();
  const [edit_type, setEdit_type] = useState("add");
  // 角色-级别筛选
  const search_data = () => {
    setRole_action_list([]);
    setRole_user_list([]);
    setClicked_role_id("");
    setClicked_role_obj({});
    getData();
  };

  // 获取角色列表
  const getData = async () => {
    let upMsg = {
      role_grade: action_value,
      op_type: "list_role",
      company_id: local_company_object.id,
      company: local_company_object.company,
    };
    setSpinning(true);
    let res = await post_axios("role_manager", "m_query", upMsg);
    setSpinning(false);
    if (!res) return;
    setRole_list(res.data_rows.rows);
  };
  const columns = [
    {
      dataIndex: "idx",
      align: "center",
      width: 40,
      render: (_, record, index) => <>{index + 1}</>,
    },
    {
      title: t("system_manager.role_name_new"),
      dataIndex: "role_name",
      align: "center",
    },
    {
      title: t("system_manager.role_grade_new"),
      align: "center",
      render: (_, record) => (
        <>
          <div>{grade_object[`${record.role_grade}`]}</div>
        </>
      ),
    },
    {
      title: t("system_manager.operator"),
      dataIndex: "cuser",
      align: "center",
    },
    {
      title: t("system_manager.operation_time"),
      dataIndex: "ctime",
      align: "center",
    },
  ];
  // 查询菜单权限及级别数据
  const get_role_action_menu = async () => {
    let upMsg = {
      op_type: "action",
    };
    let res = await post_axios("login_get_menu", "menu", upMsg);
    if (!res) return;
    let role_action = res.data.array_role.map((item) => {
      return {
        label: text_check(item),
        value: item.role_grade,
        key: item.role_grade,
      };
    });
    setRole_action_array(role_action);
    setMenu_power_array(res.data.array_menu);
    setMenu_power_array_initial(res.data.array_menu);

    //   级别对应中英文对象
    let grade_map_arr = {};
    res.data.array_role.forEach((ele) => {
      grade_map_arr[`${ele.role_grade}`] = text_check(ele);
    });
    setGrade_object(grade_map_arr);
  };

  // 角色列表点击
  const [clicked_role_id, setClicked_role_id] = useState("");
  const [clicked_role_obj, setClicked_role_obj] = useState();
  const role_row_click = (row) => {
    setClicked_role_id(row.role_id);
    setClicked_role_obj(row);
    get_role_action_data(row);
    get_role_user_data(row);
  };
  const edit_role_dialog_show = (value) => {
    setEdit_type(value);
    if (value === "add") {
      setEdit_role_title(t("common.add") + t("system_manager.role"));
      setMenu_power_array(JSON.parse(JSON.stringify(menu_power_array_initial)));
      setEdit_role_show(true);
    } else {
      if (clicked_role_id === "") {
        message.warning({
          content: t("system_manager.choose_one_role"),
        });
        return;
      }
      setEdit_role_title(t("common.change") + t("system_manager.role"));
      let menu_power_array = JSON.parse(
        JSON.stringify(menu_power_array_initial)
      );
      role_action_list.forEach((item) => {
        item = JSON.parse(JSON.stringify(item));
        let checked_menu_key = item.children.map((child) => child.menu_index);

        menu_power_array.forEach((menu) => {
          //menu为大类菜单，如系统管理，平台管理，其children为具体可点菜单
          menu.children.forEach((menu_child) => {
            //menu_child为每个菜单的子菜单的列表 包括例如  人员组织架构，角色管理，用户管理，操作日志
            if (menu_child.msg_cn === item.msg_cn) {
              // 找到目标菜单赋予权限
              menu_child["child_checked"] = checked_menu_key;
              if (checked_menu_key.length !== menu_child.children.length) {
                //选中的和children数组长度不同代表没有全选中，将半选中设为true，选中设为false
                menu_child["indeterminate"] = true;
                menu_child["checked"] = false;
              } else {
                menu_child["indeterminate"] = false;
                menu_child["checked"] = true;
              }
            }
          });
        });
      });
      setMenu_power_array(menu_power_array);
      setEdit_role_show(true);
    }
  };

  // 查询角色授权的模块
  const get_role_action_data = async (row) => {
    let upMsg = {
      op_type: "list_role_action",
      role_id: row ? row.role_id : clicked_role_id,
      company_id: local_company_object.id,
      company: local_company_object.company,
    };
    setSpinning(true);
    let res = await post_axios("role_manager", "m_query", upMsg);
    setSpinning(false);
    if (!res) return;
    setRole_action_list(res.data.array_menu);
  };
  //   查询角色下的用户
  const get_role_user_data = async (row) => {
    let upMsg = {
      role_id: row ? row.role_id : clicked_role_id,
      company_id: local_company_object.id,
      company: local_company_object.company,
    };
    let res = await post_axios("role_manager", "m_query_user", upMsg);
    if (!res) return;
    setRole_user_list(res.data_rows.rows);
  };

  const delete_role = () => {
    if (clicked_role_id === "") {
      message.warning({
        content: t("system_manager.choose_one_role"),
      });
      return;
    }
    confirm({
      icon: <ExclamationCircleFilled />,
      content: <p>{t("system_manager.sure_to_delete")}</p>,
      onOk: async () => {
        let menu_power_array = JSON.parse(
          JSON.stringify(menu_power_array_initial)
        );
        role_action_list.forEach((value) => {
          const item = JSON.parse(JSON.stringify(value));
          let checked_menu_key = item.children.map((child) => child.menu_index);

          menu_power_array.forEach((menu) => {
            //menu为大类菜单，如系统管理，平台管理，其children为具体可点菜单
            menu.children.forEach((menu_child) => {
              //menu_child为每个菜单的子菜单的列表 包括例如  人员组织架构，角色管理，用户管理，操作日志
              if (menu_child.msg_cn === item.msg_cn) {
                // 找到目标菜单赋予权限
                menu_child["child_checked"] = checked_menu_key;
                if (checked_menu_key.length !== menu_child.children.length) {
                  //选中的和children数组长度不同代表没有全选中，将半选中设为true，选中设为false
                  menu_child["indeterminate"] = true;
                  menu_child["checked"] = false;
                } else {
                  menu_child["indeterminate"] = false;
                  menu_child["checked"] = true;
                }
              }
            });
          });
        });
        let updata_arr = [];
        menu_power_array.forEach((item) => {
          item.children.forEach((child) => {
            if (child.child_checked && child.child_checked.length !== 0) {
              updata_arr = updata_arr.concat(child.child_checked);
            }
          });
        });
        let upMsg = {
          role_name: clicked_role_obj.role_name,
          role_grade: clicked_role_obj.role_grade,
          role_id: clicked_role_id,
          array_action: updata_arr,
          company_id: local_company_object.id,
          company: local_company_object.company,
        };
        setSpinning(true)
        let res = await post_axios("role_manager", "m_del", upMsg);
        setSpinning(false)
        if (!res) return;
        message.success({
          content: t("common.delete_success"),
        });
        search_data();
      },
      onCancel() {
        console.log("Cancel");
      },
    });
  };

  useEffect(() => {
    // 挂载后或者更新后的操作
    getData().then(() => {
      const tabBoxHeight =
        document.getElementsByClassName("role_manager")[0].scrollHeight;
      const tableHeight = tabBoxHeight - 42 - 30;
      setTableHeight(tableHeight);
    });
    get_role_action_menu();
  }, []);
  return (
    <>
      <div className="role_manager modules">
        <div className="screen_ipt">
          <div className="ipt_box long_title">
            <div className="ipt_box_title">
              {t("system_manager.role_grade_new")}
            </div>
            <Select
              size="small"
              placeholder=" "
              options={role_action_array}
              value={action_value}
              onChange={(value) => setAction_value(value)}
              allowClear={true}
            />
          </div>
        </div>
        <div className="screen_btn">
          <div className="btn_box">
            {/* 添加 */}
            {menu_action.indexOf("m_add") > -1 ? (
              <Button
                size="small"
                type="text"
                icon={<PlusOutlined style={{ color: "#1677FF" }} />}
                onClick={() => edit_role_dialog_show("add")}
              >
                {text_check(user_power_lang["m_add"])}
              </Button>
            ) : (
              ""
            )}
            {/* 修改 */}
            {menu_action.indexOf("m_modify") > -1 ? (
              <Button
                size="small"
                type="text"
                icon={<EditOutlined style={{ color: "#1677FF" }} />}
                onClick={() => edit_role_dialog_show("change")}
              >
                {text_check(user_power_lang["m_modify"])}
              </Button>
            ) : (
              ""
            )}
            {/* 删除 */}
            {menu_action.indexOf("m_del") > -1 ? (
              <Button
                size="small"
                type="text"
                icon={<DeleteOutlined style={{ color: "#1677FF" }} />}
                onClick={delete_role}
              >
                {text_check(user_power_lang["m_del"])}
              </Button>
            ) : (
              ""
            )}
            {/* 查询 */}
            {menu_action.indexOf("m_query") > -1 ? (
              <Button
                size="small"
                type="text"
                icon={<SearchOutlined style={{ color: "#1677FF" }} />}
                onClick={search_data}
              >
                {text_check(user_power_lang["m_query"])}
              </Button>
            ) : (
              ""
            )}
          </div>
        </div>
        <div className="table_box">
          <div className="noPage-table" style={{ width: "49.8vw" }}>
            <Table
              dataSource={role_list}
              size="small"
              bordered
              columns={columns}
              rowKey="role_id"
              virtual
              scroll={{
                y: tableHeight,
              }}
              rowHoverable={false}
              pagination={false}
              onRow={(record) => {
                return {
                  onClick: () => role_row_click(record), // 点击行
                };
              }}
              rowClassName={(record, index) => {
                if (record.role_id === clicked_role_id) {
                  return "row_clicked_style";
                }
              }}
            />
          </div>
          {role_user_list.length > 0 ? (
            <RolePower
              role_user_list={role_user_list}
              role_action_list={role_action_list}
              tableHeight={tableHeight}
            />
          ) : (
            ""
          )}
        </div>
      </div>
      {edit_role_show ? (
        <EditRole
          edit_role_title={edit_role_title}
          edit_role_show={edit_role_show}
          setEdit_role_show={setEdit_role_show}
          search_data={search_data}
          edit_type={edit_type} //操作类型 添加/修改
          local_company_object={local_company_object}
          clicked_role_obj={clicked_role_obj}
          role_action_array={role_action_array} //角色select列表
          menu_power_array={menu_power_array} //权限列表
          clicked_role_id={clicked_role_id} //修改角色权限用到的角色id
        />
      ) : (
        ""
      )}
    </>
  );
}
